Maximal Square

Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing all 1’s and return its area.

For example, given the following matrix:

  1. 1 0 1 0 0
  2. 1 0 1 1 1
  3. 1 1 1 1 1
  4. 1 0 0 1 0

Return 4.

Solution:

  1. public class Solution {
  2. public int maximalSquare(char[][] a) {
  3. if (a == null || a.length == 0 || a[0].length == 0)
  4. return 0;
  5. int max = 0;
  6. int n = a.length;
  7. int m = a[0].length;
  8. // recurrence formula:
  9. // dp(i, j) = min{ dp(i-1, j-1), dp(i-1, j), dp(i, j-1) }
  10. int[][] dp = new int[n + 1][m + 1];
  11. for (int i = 1; i <= n; i++) {
  12. for (int j = 1; j <= m; j++) {
  13. if (a[i - 1][j - 1] == '1') {
  14. dp[i][j] = Math.min(
  15. dp[i - 1][j - 1],
  16. Math.min(dp[i - 1][j], dp[i][j - 1])
  17. ) + 1;
  18. max = Math.max(max, dp[i][j]);
  19. }
  20. }
  21. }
  22. // return the area
  23. return max * max;
  24. }
  25. }